/*******************************************************************************
Author:    Jake Jares
Date:      2021.09.10
Inputs:    "Sampling Frame Demographic Means for Post-Strat Weights.dta"
           "Survey Respondent Data for Regression Analyses.dta"
		   
Ouputs:    "Regression Data with Post-Strat Weights.dta"

Note: Programs requires that the Stata ebalance package first be installed.
*******************************************************************************/


#delimit;
clear; capture log close; macro drop _all; program drop _all; set more off; 
set type double; set varabbrev off;
#delimit cr

// CHANGE THE FOLLOWING FILEPATH TO REFLECT LOCATION OF REPLICATION FOLDER
// (Note that Windows machines use "\" characters for filepaths)
global PROJECT_DIR "/Users/jjares/Documents/research/Farm Subsidies/replication_materials"
global DATA "${PROJECT_DIR}/data"

// Get post-stratification target moments from sampling frame demographics
use "${DATA}/Sampling Frame Demographic Means for Post-Strat Weights.dta", clear
rename age_on_ED_2020 age_2020
* Getting rid of "less than high school" as omitted category
local education_fields = "high_school some_college_or_assoc bachelors_degree graduate_degree"
* Getting rid of "metro_over_1_million" as omitted category
local geography_fields = "nonmetro_rural nonmetro_urban metro_under_1_million"
local moments_varlist = "male age_2020 `education_fields' `geography_fields'"

display "`moments_varlist'"

local count  = 1
foreach match_field in `moments_varlist' {
	display "`match_field'"
	display "hello"
	local mean_match_field = `match_field'[1]
	if (`count' == 1){	
		local manual_targets = "`mean_match_field'"
	}
	else {
		local manual_targets = "`manual_targets'" + " `mean_match_field'"
	}
	local count = `count' + 1	
}
display "`manual_targets'"

// Read in Survey Data for Analysis and Create Fields for Post-Stratification Moment Matching
use "${DATA}/Survey Respondent Data for APSR Analyses.dta", clear
keep if complete & !missing(age_2020) & !missing(gender) & !missing(RUCC_2013) & !missing(education)
ebalance `moments_varlist', manualtargets(`manual_targets')
rename _webal entropy_weight
save "${DATA}/Regression Data with Post-Strat Weights.dta", replace
